package com.feng.fengmall.auth2.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.feng.fengmall.auth2.feign.MemberFeignService;
import com.feng.fengmall.auth2.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object user = session.getAttribute(AuthConstant.LOGIN_USER);
        if (user==null){
            return "login";
        }else {
            return "redirect:http://localhost:10000";
        }
    }

    @Autowired
    private MemberFeignService memberFeignService;

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);

        if (login.getCode()==0){
            MemberRespVo user = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthConstant.LOGIN_USER,user);
            return "redirect:http://localhost:10000";
        }else {
            Map<String,String> error=new HashMap<>();
            error.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("error",error);
            return "redirect:http://localhost:20000/login.html";
        }
    }
}
